import * as vscode from 'vscode'
import * as path from 'path'
import { JutroConfig } from './types'

import getCreatePageCmd from './modules/create-page-cmd'
import getCodeCompletionProvider from './modules/code-completion-provider'
import getExtractTextCmd from './modules/extract-text-cmd'

function loadWorkspaceConfig(): JutroConfig | {} {
  const workspaceFolders = vscode.workspace.workspaceFolders
  if (!workspaceFolders) {
    vscode.window.showErrorMessage('No workspace opened!')
    return {}
  }
  const configFilePath = path.join(
    workspaceFolders[0].uri.fsPath,
    '.jutro.config.js'
  )
  try {
    const configData = require(configFilePath)
    vscode.window.showInformationMessage('jutro config file loaded!')
    return configData || {}
  } catch (error) {
    vscode.window.showInformationMessage(
      'No jutro config file found, will use default presets.'
    )
    return {}
  }
}

export function activate(context: vscode.ExtensionContext) {
  const projectConfig = loadWorkspaceConfig()

  const createPageCmd = getCreatePageCmd(projectConfig!)
  const completionProvider = getCodeCompletionProvider(projectConfig)
  const extractTxtCmd = getExtractTextCmd(projectConfig!)

  context.subscriptions.push(createPageCmd, completionProvider, extractTxtCmd)
}
